package code.servlet;

import code.service.UserService;
import code.util.EncryptionUtil;
import code.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: cheny
 * Date: 12-3-4
 * Time: 下午6:13
 */
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        login(req, resp);
    }


    private void login(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/xml; charset=UTF-8");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if(StringUtil.isEmpty(username)||StringUtil.isEmpty(password)){
                response.getWriter().print("2|用户名或密码为空");
                return;
            }

            boolean flag = UserService.hasUser(username, EncryptionUtil.md5(password));
            if (flag) {
                response.getWriter().print("0|登录成功");
            }

            else {
                response.getWriter().print("1|用户名或密码错误");
            }
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}
